package com.util;

import java.util.Enumeration;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//6辆汽车，停3个车位
public class SemaphoreDemo {
    public static void main(String[] args) {
        //创建Semaphore，设置许可数量

        //模拟描述活动  7个秒杀名额
        Semaphore semaphore = new Semaphore(7);

        ConcurrentHashMap<String, Object> stringObjectConcurrentHashMap = new ConcurrentHashMap<>();


        //模拟百万流量在线抢 1万
        for (int i = 1; i <= 10000; i++) {
            new Thread(() -> {
                try {
                    //模拟手速  网速等随机因素导致慢了
                    int random = (int) (Math.random() * 5) + 1;
                    TimeUnit.SECONDS.sleep(random);

                    //抢占
                    semaphore.acquire();

                    System.out.println(Thread.currentThread().getName() + " 抢到了商品");

                    //设置付款时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));

                    System.out.println(Thread.currentThread().getName() + " 付款成功");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    int random = (int) (Math.random() * 1000) + 1;

                    //考虑时间
                    try {
                        TimeUnit.MINUTES.sleep(new Random().nextInt(5));
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    //模拟一个退单情况
                    if (random <= 500) {
                        System.out.println(Thread.currentThread().getName() + "已退单");

                        //释放
                        semaphore.release();
                    } else {
                        stringObjectConcurrentHashMap.put(Thread.currentThread().getName(), 1);
                    }
                }
            }, String.valueOf(i)).start();
        }

        Enumeration<String> keys = stringObjectConcurrentHashMap.keys();
        while (keys.hasMoreElements()) {
            System.out.println("恭喜" + keys.nextElement() + "抢到了了本次秒杀商品");
        }
    }
}
